﻿using System;
using System.Runtime.InteropServices;
using System.Timers;

namespace DevTools.PopupKiller.Components
{
    /// <summary>
    /// 주기적으로 특정 팝업창을 검사하여 닫는 역할을 구현한 클래스
    /// </summary>
    public class Killer
    {
        #region Platform invoking
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        #endregion

        public string[] PopupCaptions { get; set; }

        private Timer _timer;

        /// <summary>
        /// 팝업창 닫기를 시작한다.
        /// </summary>
        public void Start(string[] popupCaptions, double interval)
        {
            PopupCaptions = popupCaptions;

            _timer = new Timer(interval);
            _timer.Elapsed += Timer_Elapsed;

            _timer.Start();
        }

        /// <summary>
        /// 팝업창 닫기를 중지한다.
        /// </summary>
        public void Stop()
        {
            _timer.Stop();
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Stop();

            foreach (var popupCaption in PopupCaptions)
            {
                IntPtr ptr = FindWindow(null, popupCaption);
                if (ptr != IntPtr.Zero)
                    SendMessage(ptr, 0x10, IntPtr.Zero, IntPtr.Zero);
            }

            _timer.Start();
        }
    }
}